<?php
/**
 * 文章分类
 * User: cxm
 * Date: 2019/10/30
 * Time: 13:43
 */
namespace App\Http\Controllers\Admin\Article;
use App\Http\Controllers\Admin\Controller;
use App\Models\Article;
use App\Models\ArticleClass;
use DB,Validator;
use Illuminate\Http\Request;

class ArticleClassController extends Controller
{
    /**
     * 文章咨询分类列表(分页)
     * URL POST:/admin/article/classify/get-lists
     * @param Request $request
     * @param string start_time 搜索开始时间
     * @param string end_time 搜索结束时间
     * @param int pid 父级Id
     * @param string keyword 关键字
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request) {
        $params = $request->only(['start_time','end_time','pid','keyword','page','limit']);
        $pid = isset($params['pid']) ? $params['pid'] : 0;
        // 等级
        $params['where'][] = ['pid',$pid];
        // 搜索时间
        if (!empty($params['start_time'])) {
            $params['where'][] = ['created_at','>=',$params['start_time']];
        }
        if (!empty($params['end_time'])) {
            $params['where'][] = ['created_at','<=',$params['end_time']];
        }
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            $params['where'][] = ['name','like','%'.$keyword.'%'];
        }
        $params['orderBy'] = ['sort asc','created_at desc'];
        $data = ArticleClass::listByWhere($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 获取详情
     * URL POST:/admin/article/classify/detail
     * @param Request $request
     * @param int id 分类ID
     * @return mixed
     */
    public function detail(Request $request){
        $params = $request->only(['id']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少ID');
        }
        $data = ArticleClass::find($params['id']);
        return $this->success('查询成功',$data);
    }

    /**
     * 添加、编辑分类
     * URL POST:/admin/article/classify/store
     * @param Request $request
     * @param int id 编辑时传
     * @param string name 分类名称
     * @param int pid 父级ID
     * @param int sort 排序
     * @return mixed
     * @throws
     */
    public function store(Request $request){
        $params = $request->only(['id','pid','type','name','sort']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'name'          => ['required']
        ],[
            'name.required'         => '分类名称不能为空'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $classify = new ArticleClass();
        }else{
            $classify = ArticleClass::find($id);
            if (!$classify) {
                return $this->error('信息不存在');
            }
        }

        DB::beginTransaction();
        try{
            $classify->pid               = isset($params['pid']) ? $params['pid'] : 0;
            $classify->name              = $params['name'];
            $classify->sort              = isset($params['sort']) ? $params['sort'] : 1;
            if ($classify->save()) {
                // 更新level和path字段
                $this->refreshNews($classify->id);
            }
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 修改文字分类的pid和level字段
     * @param $id
     */
    public function refreshNews($id)
    {
        $classify     = new ArticleClass(); // 实例化User对象
        $cate         = $classify->where("id", $id)->first()->toArray(); // 找出他自己
        $table_prefix = DB::getTablePrefix();// 表前缀
        // 刚新增的分类先把它的值重置一下
        if ($cate['path'] == '') {
            ($cate['pid'] == 0) && DB::update("UPDATE {$table_prefix}article_class set  path = '0,$id', level = 1 where id = $id"); // 如果是一级分类
            DB::update("UPDATE {$table_prefix}article_class AS a ,{$table_prefix}article_class AS b SET a.path = CONCAT_WS(',',b.path,'$id'),a.level = (b.level+1) WHERE a.pid=b.id AND a.id = $id");
            $cate = $classify->where("id", $id)->first()->toArray(); // 从新找出他自己
        }

        if ($cate['pid'] == 0) { //有可能是顶级分类 他没有老爸
            $parent_cat['path']  = '0';
            $parent_cat['level'] = 0;
        } else {
            $parent_cat = $classify->where("id", $cate['pid'])->first()->toArray(); // 找出他老爸的parent_id_path
        }
        $replace_level = $cate['level'] - ($parent_cat['level'] + 1); // 看看他 相比原来的等级 升级了多少  ($parent_cat['level'] + 1) 他老爸等级加一 就是他现在要改的等级
        $replace_str   = $parent_cat['path'] . ',' . $id;
        DB::update("UPDATE `{$table_prefix}article_class` SET path = REPLACE(path,'{$cate['path']}','$replace_str'), level = (level - $replace_level) WHERE  path LIKE '{$cate['path']}%'");
    }

    /**
     * 删除分类
     * URL POST:/admin/folder/classify/delete
     * @param Request $request
     * @param array ids 科目ID
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params) || empty($params['ids'])) {
            return $this->error('缺少ID');
        }
        // 查询分类下是否有添加文章
        $is_news = Article::getNum($params['ids']);
        if ($is_news) {
            return $this->error('该分类不能删除，已存在文章');
        }
        $result = ArticleClass::whereIn('id',$params['ids'])->delete();
        if (!$result) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }
}